Welcome to Hands on deep learning!

02.03.06.01 非降维求和

但是,有时在调用函数来计算总和或均值时保持轴数不变会很有用。

import torch

A = torch.arange(20, dtype=torch.float32).reshape(5, 4)

print(A)

B= A.sum(axis=1, keepdims=True)

print(B)

返回值:

tensor([[ 0., 1., 2., 3.],

[ 4., 5., 6., 7.],

[ 8., 9., 10., 11.],

[12., 13., 14., 15.],

[16., 17., 18., 19.]])

tensor([[ 6.],

[22.],

[38.],

[54.],

[70.]])

例如,由于sum_A在对每行进行求和后仍保持两个轴,我们可以通过广播将A除以sum_A。

import torch

A = torch.arange(20, dtype=torch.float32).reshape(5, 4)

print(A)

B= A.sum(axis=1, keepdims=True)

C=A/B

print(C)

返回值:

tensor([[ 0., 1., 2., 3.],

[ 4., 5., 6., 7.],

[ 8., 9., 10., 11.],

[12., 13., 14., 15.],

[16., 17., 18., 19.]])

tensor([[0.0000, 0.1667, 0.3333, 0.5000],

[0.1818, 0.2273, 0.2727, 0.3182],

[0.2105, 0.2368, 0.2632, 0.2895],

[0.2222, 0.2407, 0.2593, 0.2778],

[0.2286, 0.2429, 0.2571, 0.2714]])

如果我们想沿某个轴计算A元素的累积总和, 比如axis=0(按行计算),可以调用cumsum函数。 此函数不会沿任何轴降低输入张量的维度。

import torch

A = torch.arange(20, dtype=torch.float32).reshape(5, 4)

print(A)

B= A.cumsum(axis=0)

print(B)

返回值:

tensor([[ 0., 1., 2., 3.],

[ 4., 5., 6., 7.],

[ 8., 9., 10., 11.],

[12., 13., 14., 15.],

[16., 17., 18., 19.]])

tensor([[ 0., 1., 2., 3.],

[ 4., 6., 8., 10.],

[12., 15., 18., 21.],

[24., 28., 32., 36.],

[40., 45., 50., 55.]])